package com.xyy.saas.payment.adapter.channel.fm.client;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xyy.saas.payment.adapter.channel.fm.config.SpringConfiguration;
import com.xyy.saas.payment.adapter.channel.fm.config.YBMSpringConfiguration;
import com.xyy.saas.payment.exception.PaymentException;
import com.xyy.saas.payment.manage.cores.enums.ResultCodeEnum;
import com.xyy.saas.payment.adapter.channel.fm.config.OpenParameters;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class SpringClient implements InitializingBean {

    private Map<String, FBankOpenApiClient> clientMap = new HashMap<>(8);

    @Autowired
    private SpringConfiguration springConfiguration;

    @Autowired
    private YBMSpringConfiguration ybmSpringConfiguration;

    public JSONObject send0(OpenParameters context, String merchantNo) throws Exception {
        String response =  send(context, merchantNo);

        if(StringUtils.isBlank(response)) {
            throw new PaymentException(ResultCodeEnum.CHANNEL_CONNECT_ERROR);
        }

        return JSON.parseObject(response);
    }

    public String send(OpenParameters openParameters, String merchantNo) throws Exception {
        return clientMap.get(merchantNo).send(openParameters);
    }

    public String getFBankPayPubKey(String merchantNo) {
        return clientMap.get(merchantNo).getConfig().fBankPayPubKey();
    }

    public String getFBankPayMerchantId(String merchantNo) {
        return clientMap.get(merchantNo).getConfig().fBankPayMerchantId();
    }

    public String getFBankPayMD5Key(String merchantNo) {
        return clientMap.get(merchantNo).getConfig().fBankPayMD5Key();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        FBankOpenApiClient ykqClient = new FBankOpenApiClient(springConfiguration);
        FBankOpenApiClient ybmClient = new FBankOpenApiClient(ybmSpringConfiguration);
        clientMap.put(springConfiguration.merchantNo(), ykqClient);
        clientMap.put(ybmSpringConfiguration.merchantNo(), ybmClient);
    }
}
